package hot100.logos1To10;

import java.util.HashMap;

/**
 * @author logos
 * date 2025/7/10 11:26
 * @version v1.0
 * @Package hot100
 */
public class logos10 {

    /**
     * 10. 和为K的子数组
     * https://leetcode.cn/problems/subarray-sum-equals-k/?envType=study-plan-v2&envId=top-100-liked
     */

    class Solution {
        public int subarraySum(int[] nums, int k) {
            int ans = 0;
            int sum = 0;
            int n = nums.length;
            HashMap<Integer, Integer> map = new HashMap<>(n + 1);
            map.put(0, 1);
            for (int i = 0; i < n; i++) {
                sum += nums[i];
                ans += map.getOrDefault(sum - k, 0);
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
            return ans;
        }
    }

}
